<!DOCTYPE html>
<!--
  ~ Copyright (C) 2018 guomw.Inc. All rights reserved.
  ~ 项目名称： mysite
  ~ 文件名称： edit.html
  ~ Date：18-10-15 下午4:46
  ~ Author: guomw
  -->
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">

<head th:include="common/head::head('编辑产品')"></head>

<body class="gray-bg">
<link href="../../resource/css/plugins/summernote/summernote.css" rel="stylesheet">
<link href="../../resource/css/plugins/summernote/summernote-bs3.css" rel="stylesheet">
<link href="../../resource/css/plugins/awesome-bootstrap-checkbox/awesome-bootstrap-checkbox.css" rel="stylesheet"/>
<link href="../../resource/hotui/css/hotui.style.override.css"
      th:href="@{/resource/hotui/css/hotui.style.override.css}" rel="stylesheet"/>
<link rel="stylesheet" href="../../resource/lib/zupload/control/css/zyUpload.css"
      th:href="@{/resource/lib/zupload/control/css/zyUpload.css}" type="text/css">
<style type="text/css">
    .menuHide {
        visibility: hidden;
    }
</style>
<div class="wrapper wrapper-content  animated fadeInRight">
    <input id="saleType" name="saleType" th:value="${saleType!=null?saleType.code:0}" type="hidden" value="1"/>
    <input id="isadmin" type="hidden" th:value="${isMerchant}"/>
    <div class="ibox float-e-margins">
        <div class="ibox-title">
            <span style="font-size:20px;font-weight:bold;">店铺商品编辑</span>
        </div>
        <div class="ibox-content" th:object="${productInfo}">
            <fieldset>
                <form method="post" action="/product/normalSave" id="editForm" class="form-horizontal">
                    <fieldset>
                        <input type="hidden" name="productId" th:value="${productInfo.productId}"/>
                        <input type="hidden" name="exclusiveUserId" th:value="${productInfo.exclusiveUserId}"/>
                        <input type="hidden" name="roomId" th:value="${productInfo.roomId}"/>
                        <input type="hidden" name="merchantId" value="1" th:value="${merchantId}"/>

                        <div class="form-group form-inline" style="display: none;">
                            <label class="col-sm-2 control-label"><font color="red">*</font> 类型</label>
                            <div class="col-sm-4">
                                <select class="form-control" name="sourceType">
                                    <option value="0">店铺商品</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group form-inline" sec:authorize="hasRole('ADMIN')"
                             style="display: flex;align-items: center;"
                             th:if="${productInfo!=null&&productInfo.merchantPO!=null}">
                            <label class="col-sm-2 control-label" style="padding-top: 0px;">所属商家</label>
                            <div class="col-sm-4">
                                <span th:text="${productInfo.merchantPO.data.title}"></span>
                            </div>
                        </div>
                        <div class="form-group form-inline">
                            <label class="col-sm-2 control-label"><font color="red">*</font> 所属类目</label>
                            <div class="col-sm-4 jsChainSelect">
                                <span>
                                    <select class="form-control first">
                                        <option value="">请选择</option>
                                    </select>
                                </span>
                                <span style="display:none;">
                                <select class="form-control second">
                                </select>
                                </span>
                                <span style="display:none;">
                                <select class="form-control third" name="catId">
                                </select>
                                </span>
                                <input type="hidden" id="hidCatTree" th:value="${catTreePath}"/>
                            </div>
                        </div>
                        <div class="form-group form-inline" style="display: block;">
                            <label class="col-sm-2 control-label"><font color="red">*</font> 销售类型</label>
                            <div class="col-sm-4">
                                <p class="form-control-static" th:text="${saleType.desc}">普通</p>
                                <input type="hidden" name="saleTypeCode" id="saleTypeCode" th:value="${saleType.code}"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label"><font color="red">*</font>商品名称</label>
                            <div class="col-sm-4">
                                <!--/*@thymesVar id="templateInfo" type="com.treasure.mall.biz.entity.product.ProductPO"*/-->
                                <input class="form-control " name="productName" id="productName" type="text" value=""
                                       th:value="${productInfo.productName}">
                            </div>
                        </div>
                        <div class="form-group form-inline">
                            <label class="col-sm-2 control-label">状态</label>
                            <div class="col-sm-4">
                                <select class="form-control" name="statusCode">
                                    <option value="1" th:selected="${productInfo.statusCode}==1">上架</option>
                                    <option value="0" th:selected="${productInfo.statusCode}==0">下架</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group form-inline" th:if="${isMerchant}">
                            <label class="col-sm-2 control-label">是否置顶</label>
                            <div class="col-sm-4">
                                <select class="form-control" name="recommendFlag">
                                    <option value="0" th:selected="${productInfo.recommendFlag}==0">否</option>
                                    <option value="1" th:selected="${productInfo.recommendFlag}==1">是</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group form-inline auction-box">
                            <label class="col-sm-2 control-label">库存</label>
                            <div class="col-sm-4">
                                <input name="store" id="store" type="text" class="form-control input-s-sm only-num"
                                       placeholder="数量" th:value="${productInfo.store}">

                                <p style="margin-left: 10px;" class="form-control-static color-danger">锁定库存：<span
                                        th:text="${productInfo.freeze}">12</span></p>
                            </div>
                        </div>
                        <div class="form-group auction-box">
                            <label class="col-sm-2 control-label"><font color="red">*</font>售价</label>
                            <div class="col-sm-4">
                                <div class="input-group">
                                    <span class="input-group-addon">¥</span>
                                    <input name="price" id="price" type="text"
                                           class="form-control input-s-sm only-float" placeholder="售价"
                                           th:value="${productInfo.price!=null?productInfo.price.stripTrailingZeros().toPlainString():''}">
                                </div>
                            </div>
                        </div>
                        <div class="form-group auction-box">
                            <label class="col-sm-2 control-label"><font color="red">*</font>市场价</label>
                            <div class="col-sm-4">
                                <div class="input-group">
                                    <span class="input-group-addon">¥</span>
                                    <input name="mktPrice" id="mktPrice" type="text"
                                           class="form-control input-s-sm only-float" placeholder="市场价"
                                           th:value="${productInfo.mktPrice!=null?productInfo.mktPrice.stripTrailingZeros().toPlainString():''}">
                                </div>
                            </div>
                        </div>
                        <div class="form-group form-inline">
                            <label class="col-sm-2 control-label"><font color="red">*</font>平台佣金抽成比例</label>
                            <div class="col-sm-4">
                                <div class="input-group">
                                    <input name="commissionRate" id="commissionRate" type="text" style="width: 50px"
                                           class="form-control input-sm input-s-sm only-float" placeholder=""
                                           th:value="${productInfo.commissionRate!=null?productInfo.commissionRate.stripTrailingZeros().toPlainString():''}">
                                    <span class="input-group-addon">%</span>
                                </div>
                                <p class="form-control-static m-l-sm color-notice" id="commissionRateTip"></p>
                            </div>
                        </div>
                        <div class="form-group form-inline">
                            <label class="col-sm-2 control-label"><font color="red"></font> 服务标签</label>
                            <div class="col-sm-4">
                                <div class="checkbox checkbox-primary" th:each="tag:${serviceTags}">
                                    <input type="checkbox" id="tag_1" th:checked="${tag.code==0}"
                                           th:disabled="${tag.code==0}" th:id="|tag_${tag.code}|" th:value="${tag.code}"
                                           name="chkServiceTag" value="1">
                                    <label for="tag_1" th:for="|tag_${tag.code}|"><font
                                            th:text="${tag.desc}">全国包邮</font></label>
                                </div>

                                <input type="hidden" name="serviceTags" id="serviceTags"
                                       th:value="${productInfo.serviceTags}"/>
                            </div>
                        </div>
                        <div sec:authorize="hasRole('ADMIN')" class="form-group form-inline">
                            <label class="col-sm-2 control-label"><font color="red"></font> 商品标签</label>
                            <div class="col-sm-4">
                                <div class="checkbox checkbox-primary" th:each="tag:${productTags}">
                                    <input type="checkbox" id="producttag_1" th:id="|producttag_${tag.code}|"
                                           th:value="${tag.code}" name="chkProductTag" value="1">
                                    <label for="producttag_1" th:for="|producttag_${tag.code}|"><font
                                            th:text="${tag.desc}">一元捡漏</font></label>
                                </div>
                                <input type="hidden" name="productTags" id="productTags"
                                       th:value="${productInfo.productTags}"/>
                            </div>
                        </div>
                        <div class="form-group form-inline">
                            <label class="col-sm-2 control-label"><font color="red">*</font> 限购数</label>
                            <div class="col-sm-4">
                                <div class="input-group">
                                    <input name="limitedNum" type="text" id="limitedNum"
                                           class="form-control input-sm input-s-sm only-num" placeholder="限购数"
                                           value="0" th:value="${productInfo.limitedNum}">
                                    <span class="input-group-addon">件</span>
                                </div>
                                <p class="form-control-static m-l-sm color-notice">填0表示不限购</p>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">商品主图</label>
                            <div class="col-sm-9">
                                <input type="hidden" name="picList" id="picList" th:value="${picList}"/>
                                <input type="file" style="display: none" id="uploadfile" name="uploadfile"
                                       readonly="readonly"
                                       class="form-control">
                                <div id="containerAbove">

                                </div>
                                <a href="javascript:pageHandler.uploadModalShow()">批量上传</a>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">视频</label>
                            <div class="col-sm-4">
                                <input type="hidden" name="video" id="video" th:value="${productInfo.video}"/>
                                <input type="file" style="display: none" id="uploadfileVideo" name="uploadfileVideo"
                                       readonly="readonly"
                                       class="form-control">
                                <a title="选择视频">
                                    <img class="videoPreview" src="../../resource/img/bg.png"
                                         onerror="this.src='/resource/img/bg.png'"
                                         style="margin-top: 10px; width:120px;height:120px;"
                                    />
                                </a>
                                <a href="javascript:pageHandler.deleteVideo()">删除</a>

                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">尺寸</label>
                            <div class="col-sm-4">
                                <input class="form-control " name="propSize" id="propSize" type="text" value="尺寸"
                                       th:value="${productInfo.propSize}">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">材质</label>
                            <div class="col-sm-4">
                                <input class="form-control " name="PropMaterial" id="PropMaterial" type="text"
                                       value="材质" th:value="${productInfo.propMaterial}">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">产地</label>
                            <div class="col-sm-4">
                                <input class="form-control " name="location" id="location" type="text" value="产地"
                                       th:value="${productInfo.location}">
                            </div>
                        </div>
                        <div class="form-group form-inline">
                            <label class="col-sm-2 control-label">重量</label>
                            <div class="col-sm-4">
                                <input type="text" name="weight" id="weight" class="form-control  input-s-sm only-float"
                                       placeholder="重量"
                                       th:value="${productInfo.weight!=null?productInfo.weight.stripTrailingZeros().toPlainString():''}">
                                <select class="form-control" name="weightUnit">
                                    <option value="G" th:selected="${productInfo.weightUnit}=='G'">G</option>
                                    <option value="KG" th:selected="${productInfo.weightUnit}=='KG'">KG</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">详情</label>
                            <div class="col-sm-6">
                                <input type="hidden" id="detailContent" name="detailContent"
                                       th:value="${productInfo.detailContent}"/>
                                <div class="ibox-content no-padding">
                                    <div class="summernote" id="description"></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-offset-5">
                            <button id="btnSubmitData" type="submit" class="btn btn-primary">保存</button>
                        </div>
                        <input type="hidden" th:value="${@resourceService.getResourceDomain()}" id="hidResourceDomain"/>
                    </fieldset>
                </form>
            </fieldset>
        </div>
    </div>

</div>

<script type="text/html" id="upload_modal">
    <div id="T_upload"></div>
    <input type="hidden" id="upload_files"/>
</script>

<footer th:include="common/footer::js"/>
<script src="../../resource/js/jquery.min.js?v=2.1.4" th:src="@{/resource/js/jquery.min.js?v=2.1.4}"></script>
<script src="../../resource/js/bootstrap.min.js?v=3.3.5" th:src="@{/resource/js/bootstrap.min.js?v=3.3.5}"></script>
<script src="../../resource/hotui/js/hot/bootstrap.hot.extra-utils-improve.js?666666"
        th:src="@{/resource/hotui/js/hot/bootstrap.hot.extra-utils-improve.js?666666}"></script>
<script src="../../resource/hotui/js/hot/bootstrap.hot.extra-init.js?20190316?1234567"
        th:src="@{/resource/hotui/js/hot/bootstrap.hot.extra-init.js?20190316(123)}"></script>
<script src="../../resource/hotui/js/content.min.js" th:src="@{/resource/hotui/js/content.min.js}"></script>


<script src="https://cdn.bootcss.com/jquery.form/4.2.2/jquery.form.min.js"></script>
<script src="/resource/lib/jquery-chain-select/jquery.chainSelect.js?xxxxx"></script>
<script src="/resource/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="/resource/lib/jquery-validation/dist/messages_cn.js"></script>

<script src="../../resource/js/plugins/prettyfile/bootstrap-prettyfile.js"></script>
<script src="/resource/js/plugins/summernote/summernote.min.js"></script>
<script src="/resource/js/plugins/summernote/summernote-zh-CN.js"></script>
<script src="/resource/lib/arttemplate/template.js"></script>
<script src="/resource/js/Math.uuid.js"></script>
<!-- 引用核心层插件 -->
<script type="text/javascript" src="../../resource/lib/zupload/core/zyFile.js"
        th:src="@{/resource/lib/zupload/core/zyFile.js}"></script>
<!-- 引用控制层插件 -->
<script type="text/javascript" src="../../resource/lib/zupload/control/js/zyUpload.js"
        th:src="@{/resource/lib/zupload/control/js/zyUpload.js}"></script>
<!-- 引用初始化JS -->
<!--<script type="text/javascript" src="demo.js"></script>-->
<script type="text/javascript" src="../../resource/lib/zupload/control/js/jqueryrotate.js"
        th:src="@{/resource/lib/zupload/control/js/jqueryrotate.js}"></script>
<script type="text/javascript" src="../../resource/lib/zupload/index.js"
        th:src="@{/resource/lib/zupload/index.js}"></script>

</body>
<script type="text/javascript" th:inline="javascript">
    const uploadUri = /*[[@{/resource/upload}]]*/  "";
    const resourceUri = /*[[@{/resource}]]*/  "";
    const commissionRate = /*[[${commissionRate}]]*/ -1;
</script>
<script type="text/javascript">
    var _RESOURCE_DOMAIN = $('#hidResourceDomain').val();
    $(function () {
        pageHandler.init();
        productPictureHandler.init();
    });

    var uploadModal = $("#upload_modal").layerModal("上传图片", function () {
        productPictureHandler.batchUpload();
    });

    var pageHandler = {
        uploadModalShow: function () {
            uploadModal.show(function () {
                $("#T_upload").zyUpload({
                    width: "650px",                 // 宽度
                    height: "400px",                 // 宽度
                    itemWidth: "120px",                 // 文件项的宽度
                    itemHeight: "100px",                 // 文件项的高度
                    url: resourceUri + "/upload",  // 上传文件的路径
                    multiple: true,                    // 是否可以多个文件上传
                    dragDrop: true,                    // 是否可以拖动上传文件
                    del: true,                    // 是否可以删除文件
                    finishDel: false,                   // 是否在上传文件完成后删除预览
                    /* 外部获得的回调接口 */
                    onSelect: function (files, allFiles) {                    // 选择文件的回调方法
                    },
                    onDelete: function (file, surplusFiles) {                     // 删除一个文件的回调方法
                    },
                    onSuccess: function (file, response) {                    // 文件上传成功的回调方法
                        let current = $("#upload_files").val();
                        let path = JSON.parse(response).data.path;
                        current += path + ",";
                        $("#upload_files").val(current);
                    },
                    onFailure: function (file) {                    // 文件上传失败的回调方法
                    },
                    onComplete: function (responseInfo) {           // 上传完成的回调方法
                    }
                });
            })
        },
        init: function () {
            this.regValidator();

            if (parseInt($("#saleType").val()) === 1) {
                $(".auction-box").hide();
                $("#store").val(1);
                $("#price").val(1);
                $("#mktPrice").val(1);
            } else {
                $(".auction-box").show();
            }


            $("#editForm").submit(function () {
                pageHandler.ajaxSubmit();
                return false;
            });
            //富文本
            var smnote = $(".summernote").summernote({
                lang: "zh-CN",
                onImageUpload: function (files, editor, $editable) {
                    hotUtil.uploadImg(files, "product", function (url, path) {
                        editor.insertImage($editable, url);
                    });
                }
            });

            $('form').each(function () {
                if ($(this).data('validator'))
                    $(this).data('validator').settings.ignore = ".note-editor *";
            });
            //上传
            $('.videoPreview').click(function () {
                $("#uploadfileVideo").click();
            });
            $('body').delegate("#uploadfileVideo", 'change', function () {
                hot.loading.show();
                hotUtil.uploadImg($("#uploadfileVideo")[0].files, "product", function (url, path) {
                    hot.loading.close();
                    $(".videoPreview").attr("src", '/resource/img/video_ok.jpg');
                    $("#video").val(url);
                });
            });
            if ($('#video').val() != '') {
                $(".videoPreview").attr("src", '/resource/img/video_ok.jpg');
            }
            //多级类目
            this.initCategory();
            this._afterLoaded();
        },
        getEditContent: function () {
            return $(".summernote").code();
        },
        setEditContent: function (content) {
            $(".summernote").code(content);
        },
        deleteVideo: function () {
            let path = $("#video").val();
            if (hot.isNullOrEmpty(path)) {
                return;
            }
            hot.ajax(resourceUri + "/delete", {
                path: path
            }, function (apiResult) {
                $("#video").val("");
                $(".videoPreview").attr("src", "/resource/img/bg.png");
            }, function () {
            }, "post");
        },
        initCategory: function () {
            var catTree = $('#hidCatTree').val();
            var first = null, second = null, third = null;
            if (catTree != '') {
                var temp = catTree.split('|');
                first = temp[0];
                if (temp.length > 1) second = temp[1];
                if (temp.length > 2) third = temp[2];
            }
            var catSelect = $('.jsChainSelect').chainSelect({
                url: '/category/getList',
                first: first,
                second: second,
                third: third,
                onInitComplete: function () {
                    var catData = catSelect.getSelectData(2);
                    if (catData === null || typeof (catData.tag) === "undefined" || catData.tag.length === 0 || parseInt(catData.tag) <= 0) {
                        catData = catSelect.getSelectData(1);
                    }
                    if (catData != null && typeof (catData.tag) != "undefined" && catData.tag != '') {
                        var tag = parseFloat(catData.tag);
                        if ($('#commissionRate').val() == '') {
                            $('#commissionRate').val(tag);
                        }
                        if (commissionRate === -1) {
                            $('#commissionRateTip').html('不得小于' + catData.tag + '%');
                        } else {
                            $('#commissionRateTip').html('不得小于' + commissionRate + '%');

                        }
                    }
                    //第1,2个select置为不可用
                    if ($("#isadmin").val().toLowerCase() == "true") {
                        $('.first').attr('disabled', 'disabled');
                        $('.second').attr('disabled', 'disabled');
                    }
                }
            });
        },
        regValidator: function () {
            $("#editForm").validate({
                ignore: ".note-editor *",
                rules: {
                    catId: {
                        required: true
                    },
                    productName: {
                        required: true
                    },
                    price: {
                        required: true
                    },
                    mktPrice: {
                        required: true
                    },
                    commissionRate: {
                        required: true,
                        max: 100
                    }
                },
                messages: {
                    commissionRate: {
                        max: "最大值不能超过100"
                    }
                },
                errorClass: 'help-block help-block-error',
                focusInvalid: true,
                highlight: function (element) {
                },
                success: function (label, element) {
                    $(element).closest('.form-group').removeClass('has-error');
                    $(element).attr("title", "").tooltip("hide");
                },
                errorPlacement: function (error, element) {
                    if ($(element).next("div").hasClass("tooltip")) {
                        $(element).attr("data-original-title", $(error).text()).tooltip("show");
                    } else {
                        $(element).attr("title", $(error).text()).tooltip("show");
                    }
                },
                submitHandler: function (form) {
                }
            });
        },
        setButtonDisabled: function (flag) {
            if (flag) {
                $('#btnSubmitData').attr('disabled', 'disabled').html('保存中');
            } else {
                $('#btnSubmitData').removeAttr('disabled').html('保存');
            }
        },
        _afterLoaded: function () {
            this.setEditContent($('#detailContent').val());
            var serviceTagsStr = $('#serviceTags').val();
            $('input[name="chkServiceTag"]').each(function () {
                if (serviceTagsStr.indexOf(',' + $(this).val() + ',') != -1) {
                    $(this).attr('checked', 'checked');
                }
            });
            var productTagsStr = $('#productTags').val();
            $('input[name="chkProductTag"]').each(function () {
                if (productTagsStr.indexOf(',' + $(this).val() + ',') != -1) {
                    $(this).attr('checked', 'checked');
                }
            });
        },
        _preSubmit: function () {
            $('#detailContent').val(this.getEditContent());
            var serviceTags = [];
            $('input[name="chkServiceTag"]:checked').each(function () {
                serviceTags.push($(this).val());
            });
            $('#serviceTags').val(',' + serviceTags.join(',') + ',');

            var productTags = [];
            $('input[name="chkProductTag"]:checked').each(function () {
                productTags.push($(this).val());
            });
            $('#productTags').val(',' + productTags.join(',') + ',');
            $('#picList').val(JSON.stringify(productPictureHandler.getData()));
        },
        ajaxSubmit: function () {
            var self = this;
            self._preSubmit();
            $("#editForm").ajaxSubmit({
                resetForm: false,
                beforeSubmit: function (formData, jqForm, options) {
                    if (!$("#editForm").valid()) return false;
                    layer.load();
                    self.setButtonDisabled(true);
                },
                type: "post",
                dataType: "json",
                success: function (rep) {
                    hot.loading.close();
                    if (rep.resultCode === 2000) {
                        layer.close();

                        layer.msg("保存成功");
                        setTimeout(function () {
                            self.setButtonDisabled(false);
                            parent.refreshTab("/product/normalList?saleType=" + $("#saleTypeCode").val());

                            parent.closeActiveTab();
                        }, 800);
                    } else {
                        self.setButtonDisabled(false);
                        layer.closeAll();
                        layer.alert(rep.resultMsg, {icon: 5});
                    }
                },
                error: function () {
                    layer.closeAll();
                    layer.alert("网络错误，请稍候再试。", {icon: 5});
                    self.setButtonDisabled(false);
                }
            });
        }
    };

    function _appendResourceDomain(path) {
        if (path.indexOf('http://') !== -1 || path.indexOf('https://') !== -1) {
            return path;
        }
        return _RESOURCE_DOMAIN + path;
    }

    function getContainer() {
        return $('#containerAbove');
    }

    var BLANK_URL = "/resource/img/bg.png";
    var productPictureHandler = {
        picItemRender: null,
        data: [],
        _currentUid: '',
        _currentType: 0,
        init: function () {
            this.initEvent();
            var __data = JSON.parse($('#picList').val());
            var mockData = [];
            for (var i = 0; i < __data.length; i++) {
                mockData.push({
                    uid: Math.uuidFast(),
                    url: _appendResourceDomain(__data[i]),
                    type: 0
                })
            }
            this.data = mockData;
            this.picItemRender = template.compile($('#picItemTemplate').html());
            this.render();
            this.appendBlank(0);
            this._lastMenuHidden();
        },
        batchUpload: function () {
            var self = this;
            let files = $("#upload_files").val();
            files = files.substring(0, files.length - 1);
            let fileArray = files.split(",");

            var mockData = [];

            $.each(fileArray, function (o, item) {
                mockData.push({
                    uid: Math.uuidFast(),
                    url: _appendResourceDomain(item),
                    type: 0
                });
            });
            this.data = mockData;
            this.picItemRender = template.compile($('#picItemTemplate').html());
            this.render(true);
            this.appendBlank(0);
            this._lastMenuHidden();
            uploadModal.hide();
        },
        initEvent: function () {
            var self = this;

            $(document).on('click', '.imgPreview', function () {
                self._currentUid = $(this).attr('data-uid');
                self._currentType = $(this).attr('data-type');
                $("#uploadfile").click();
            });
            $('body').delegate("#uploadfile", 'change', function () {
                hotUtil.loading.show();
                hotUtil.uploadImg($("#uploadfile")[0].files, "product", function (url, path) {
                    hotUtil.loading.close();
                    self.uploadCallback({uid: self._currentUid, type: self._currentType, url: url});
                });
            });
        },
        load: function () {

        },
        render: function (isAppend) {
            this._render({rows: this.data}, 0, isAppend);
        },
        _render: function (data, type, isAppend) {
            if (isAppend) {
                getContainer().append(this.picItemRender(data));
                return;
            }
            getContainer().html(this.picItemRender(data));
        },
        _lastMenuHidden: function () {
            getContainer().find('.csMenuGroup').removeClass('menuHide');
            getContainer().find('.csMenuGroup:last').addClass('menuHide');
        },
        appendBlank: function () {
            if (getContainer().find('.imgPreview').length > 8) {//目前最多9个！！！
                return false;
            }
            getContainer().append(this.picItemRender({
                rows: [{
                    uid: Math.uuidFast(),
                    url: BLANK_URL
                }]
            }));
            this._lastMenuHidden();
            return true;
        },
        getData: function () {
            var _data = [];
            getContainer().find('input[name="csPic"]').each(function () {
                if ($(this).val() != BLANK_URL) {
                    _data.push($(this).val());
                }
            });
            return _data;
        },
        delete: function (self) {
            var _self = this;
            $('#wrapper_' + $(self).attr('data-uid')).fadeOut(function () {
                $(this).remove();
                var existBlank = false;

                getContainer().find('.imgPreview').each(function () {
                    if ($(this).attr('src') == BLANK_URL) {
                        existBlank = true;
                        return false;
                    }
                });
                if (!existBlank) {
                    _self.appendBlank();
                }
            });

        },
        uploadCallback: function (item) {
            $('#csPic_' + item.uid).val(item.url);
            $('#imgPreview_' + item.uid).attr('src', _appendResourceDomain(item.url));
            $('#csMenuGroup_' + item.uid).removeClass('menuHide');
            $('#href_' + item.uid).attr('href', _appendResourceDomain(item.url));
            var lastUid = getContainer().find('.csMenuGroup:last').attr('data-uid');
            if (lastUid === item.uid) {
                var a = this.appendBlank(item.type);
                if (a) {
                    this._lastMenuHidden();
                }
            }
        }
    };
</script>
</html>
<script type="text/tmpl" id="picItemTemplate">
    {{each rows as row}}
        <div style="float: left; margin-right:10px;" id="wrapper_{{row.uid}}">
            <input type="hidden" name="csPic" id="csPic_{{row.uid}}" value="{{row.url}}" data-uid="{{row.uid}}" data-type="{{row.type}}"/>
            <a title="选择图片">
                <img class="imgPreview" id="imgPreview_{{row.uid}}" data-uid="{{row.uid}}" data-type="{{row.type}}" src="{{row.url}}"
                     onerror="this.src='/resource/img/bg.png'"
                     style="margin-top: 10px; width:150px;height:150px;"/>
            </a>
            <div style="text-align: center;padding-top: 8px;" class="csMenuGroup" id="csMenuGroup_{{row.uid}}" data-uid="{{row.uid}}">
                <a href="{{row.url}}" target="_blank" id="href_{{row.uid}}">
                <button
                        type="button" data-uid="{{row.uid}}"
                        class="btn btn-white btn-xs m-b-none">浏览
                </button></a>&nbsp;&nbsp;&nbsp;
                <a href="javascript:;">
                <button onclick="productPictureHandler.delete(this)" data-type="{{row.type}}"
                        type="button" data-uid="{{row.uid}}"
                        class="btn btn-white btn-xs m-b-none">删除
                </button></a>
            </div>
        </div>
    {{/each}}
</script>